#include "AssemblyRegistration.h"

#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#elif defined( MACOSX )
#include "CoreFoundation/CoreFoundation.h"
#endif

using namespace Hiranipra;
using namespace Hiranipra::HCM;

#ifdef WIN32

#define IMPORT_FUNCTION( module, name ) name##_fn name = ( name##_fn )GetProcAddress( module, #name )
bool Hiranipra::HCM::HCMRegisterAssembly( ComponentRegistry& registry, wstring assemblyPath )
{
	HMODULE module = LoadLibrary( assemblyPath.c_str() );
	if( module == NULL )
		return false;
	IMPORT_FUNCTION( module, HCMRegisterComponents );
	if( HCMRegisterComponents == NULL )
	{
		FreeLibrary( module );
		return false;
	}
	HCMRegisterComponents( registry );
	return true;
}

#elif defined( MACOSX )

#define IMPORT_FUNCTION( bundle, name ) name##_fn name = ( name##_fn )CFBundleGetFunctionPointerForName( bundle, CFSTR( #name ) );
bool Hiranipra::HCM::HCMRegisterAssembly( ComponentRegistry& registry, wstring assemblyPath )
{
	string cassemblyPath = NarrowString( assemblyPath );
	CFStringRef path = CFStringCreateWithCString( NULL, cassemblyPath.c_str(), kCFStringEncodingUTF8 );
	CFURLRef bundleURL = CFURLCreateWithFileSystemPath(
		kCFAllocatorDefault,
		path,
		kCFURLPOSIXPathStyle,
		true );
	CFRelease( path );
	CFBundleRef bundle = CFBundleCreate( kCFAllocatorDefault, bundleURL );
	CFRelease( bundleURL );
	if( bundle == NULL )
		return false;
	IMPORT_FUNCTION( bundle, HCMRegisterComponents );
	if( HCMRegisterComponents == NULL )
	{
		CFBundleUnloadExecutable( bundle );
		CFRelease( bundle );
		return false;
	}
	HCMRegisterComponents( registry );
	return true;
}

#endif
